package ar.edu.uba.fi.jmit.monitorengine.core;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import ar.edu.uba.fi.jmit.integrationcommons.Event;
import ar.edu.uba.fi.jmit.monitorengine.backend.shared.dto.EventDTO;
import ar.edu.uba.fi.jmit.receiver.ReceiverObserver;

public class EventServiceManager implements ReceiverObserver {
	
	protected static EventServiceManager instance = null; 
	private long id = 1;
	private LinkedList<EventDTO> eventDTOs = new LinkedList<EventDTO>();
	
	public List<EventDTO> getRangeEventDTOs(int from, int to){
		if (to > eventDTOs.size())
			to = eventDTOs.size();
		if (from < 0)
			throw new RuntimeException("Argument From must be lower than 0");
		
		return eventDTOs.subList(from, to);
	}
	
	public LinkedList<EventDTO> getEventDTOs() {
		return this.eventDTOs;
	}
	
	public long getCountEventDTOs(){
		return this.eventDTOs.size(); 
	}
	
	public static EventServiceManager getInstance() {
		if (instance == null) {
			instance = new EventServiceManager();
		}
		return instance;
	}

	protected EventServiceManager() {
		
	}

	@Override
	public void onRecivedEvent(Event event) {
		EventDTO dto = new EventDTO();
		dto.setEventDate(getNewDate());
		dto.setId(id);
		id++;
		dto.setPriority(event.getPriority().name());
		dto.setSource(event.getSource());
		
		eventDTOs.addFirst(dto);
	}

	protected Date getNewDate() {
		return new Date();
	}

	public void cleanEvents() {
		eventDTOs = new LinkedList<EventDTO>();
	}
}
